package com.gopay.checkorder.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.CibConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.cib.ebank.CibMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * 兴业B2C订单查询
 * 
 * @CheckOrderCibB2cImpl.java
 * @author zhengxue
 * @2014-11-21 上午10:46:24 www.gopay.com.cn Inc.All rights reserved.
 */
public class CheckOrderCibB2cImpl implements BankOrderService {
    private final static Logger logger = LoggerFactory.getLogger("CIB");

    @Resource(name = "bankClient")
    private BankInteractRemoteService bankClient;

    @Override
    public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
        CheckOrderResult checkOrderResult = new CheckOrderResult();
        checkOrderResult.setSuccess(false);
        checkOrderResult.setOrderId(bankOrder.getOrderId());

        CibMessage base = new CibMessage();
        base.setOrderId(bankOrder.getOrderId());
        base.setBankOrderId(bankOrder.getOutOrderId());
        base.setBank(BankConstants.BANK_LOGO_CIB);
        base.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
        base.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));

        Result result = new Result();
        try {
            result = bankClient.query(base);
            if (result == null || !result.isSuccess() || result.getDefaultModel() == null) {
                logger.error("b2c bankClient fail.");
                if (result == null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())) {
                    BankCountDownLatch.failIncrease(bankOrder.getBankCode());
                    checkOrderResult.setCommunicateError(true);
                }
                logger.error(ToStringBuilder.reflectionToString(result, ToStringStyle.DEFAULT_STYLE));
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
                checkOrderResult.setErrMsg("系统返回对账结果为空");
                return checkOrderResult;
            }
            CibMessage res = (CibMessage) result.getDefaultModel();
            if (res == null) {
                // 查询订单为空
                logger.error("b2c fail:orderId:" + bankOrder.getOrderId() + " errcode:"
                        + ProcCodeConstants.PROC_CODE_100E6022 + " err:bis query is null.");
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
                checkOrderResult.setErrMsg("银行返回对账结果为空");
                return checkOrderResult;
            }
            if (!StringUtils.isEmpty(res.getCode())) {
                // 查询订单错误
                logger.error("b2c fail:orderId:" + bankOrder.getOrderId() + " errcode:" + res.getCode() + " err:"
                        + res.getMsg());
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
                checkOrderResult.setErrMsg(res.getMsg());
                return checkOrderResult;
            }
            if (!StringUtils.isEmpty(res.getOrderStatus())) {
                // 订单状态成功(订单已支付)
                if (CibConstants.ORDER_STATE_PAYMENT.equals(res.getOrderStatus())) {
                    checkOrderResult.setSuccess(true);
                    InAccInfo accInfo = new InAccInfo();
                    accInfo.setOrderId(bankOrder.getOrderId());
                    accInfo.setAmount(res.getAmount());
                    accInfo.setRetCode("00");
                    accInfo.setCardType(BankCardType.Unknown.toString());
                    checkOrderResult.setAccInfo(accInfo);
                    logger.error("兴业银行B2C订单:" + bankOrder.getOutOrderId() + ",交易成功返回信息: 已支付" + ",查到的订单状态:"
                            + res.getOrderStatus());
                }
                // 订单状态成功(订单已结算)
                else if (CibConstants.ORDER_STATE_SETTLEMENT.equals(res.getOrderStatus())) {
                    checkOrderResult.setSuccess(true);
                    InAccInfo accInfo = new InAccInfo();
                    accInfo.setOrderId(bankOrder.getOrderId());
                    accInfo.setAmount(res.getAmount());
                    accInfo.setRetCode("00");
                    accInfo.setCardType(BankCardType.Unknown.toString());
                    checkOrderResult.setAccInfo(accInfo);
                    logger.error("兴业银行B2C订单:" + bankOrder.getOutOrderId() + ",交易成功返回信息: 已结算" + ",查到的订单状态:"
                            + res.getOrderStatus());
                }
                // 订单状态暂不处理(订单待支付)
                else if (CibConstants.ORDER_STATE_WAITAPAY.equals(res.getOrderStatus())) {
                    logger.error("兴业银行B2C订单:" + bankOrder.getOutOrderId() + ",交易返回信息: 待支付" + ",暂不进行账务处理,查到的订单状态:"
                            + res.getOrderStatus());
                    checkOrderResult.setErrMsg("订单待支付");
                }
                // 订单状态暂不处理(订单部分退款)
                else if (CibConstants.ORDER_STATE_PARTREFUND.equals(res.getOrderStatus())) {
                    logger.error("兴业银行B2C订单:" + bankOrder.getOutOrderId() + ",交易返回信息: 部分退款" + ",暂不进行账务处理,查到的订单状态:"
                            + res.getOrderStatus());
                    checkOrderResult.setErrMsg("订单部分退款");
                }
                // 订单状态暂不处理(订单全额退款)
                else if (CibConstants.ORDER_STATE_ALLREFUND.equals(res.getOrderStatus())) {
                    logger.error("兴业银行B2C订单:" + bankOrder.getOutOrderId() + ",交易返回信息: 全额退款" + ",暂不进行账务处理,查到的订单状态:"
                            + res.getOrderStatus());
                    checkOrderResult.setErrMsg("订单全额退款");
                }
                // 订单状态失败处理(订单已撤销)
                else if (CibConstants.ORDER_STATE_CANCEL.equals(res.getOrderStatus())) {
                    // 失败处理
                    checkOrderResult.setBankFailure(true);
                    logger.error("兴业银行B2C订单:" + bankOrder.getOutOrderId() + ",交易返回信息: 已撤销" + ",暂不进行账务处理,查到的订单状态:"
                            + res.getOrderStatus());
                    checkOrderResult.setErrMsg("订单已撤销");
                }
                // 订单状态失败处理(订单支付失败）
                else if (CibConstants.ORDER_STATE_FAIL.equals(res.getOrderStatus())) {
                    checkOrderResult.setBankFailure(true);
                    logger.error("兴业银行B2C订单:" + bankOrder.getOutOrderId() + ",交易返回信息: 支付失败" + ",暂不进行账务处理,查到的订单状态:"
                            + res.getOrderStatus());
                    checkOrderResult.setErrMsg("订单支付失败");
                } else {
                    logger.error("交易结果未明确");
                    checkOrderResult.setErrMsg("交易结果未明确");
                }
            } else {
                logger.error(" CIB B2C orderId:" + bankOrder.getOrderId() + ",returnMsg:  not found order");
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
                checkOrderResult.setErrMsg("银行返回订单未查到");
            }
            return checkOrderResult;
        } catch (Exception e) {
            logger.error("b2c bankClient fail.", e);
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
            checkOrderResult.setErrMsg("系统对账异常");
            return checkOrderResult;
        }
    }

	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}

}
